﻿
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace WebApiExtend
{
    /// <summary>
    /// 登录token swagger添加参数
    /// </summary>
    public class SwaggerHeaderFilter : IOperationFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            #region 注释
            //var isAuthorized = context.MethodInfo.GetCustomAttributes(typeof(AuthorizeAttribute), false);
            //if (isAuthorized == null || isAuthorized.Length == 0)
            //{
            //    isAuthorized = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ApiDescription.ActionDescriptor).ControllerTypeInfo.GetCustomAttributes(typeof(LoginFilter), false);
            //}

            //if (isAuthorized != null && isAuthorized.Length >= 1)
            //{
            //    if (operation.Parameters == null)
            //    {
            //        operation.Parameters = new List<OpenApiParameter>();
            //    }

            //    operation.Parameters.Add(new OpenApiParameter
            //    {
            //        Name = "token",
            //        In = ParameterLocation.Header,
            //        //Description = "令牌",
            //        Required = false,
            //        //Schema = new OpenApiSchema
            //        //{
            //        //    Type = "string",
            //        //    Default = new OpenApiString("Bearer ")
            //        //}
            //    });
            //} 
            #endregion

            if (operation.Parameters == null)
            {
                operation.Parameters = new List<OpenApiParameter>();
            }

            operation.Parameters.Add(new OpenApiParameter
            {
                Name = "token",
                In = ParameterLocation.Header,
                Description = "登录token",
                Required = false,
                Schema = new OpenApiSchema
                {
                    Type = "string",
                    //Default = new OpenApiString("Bearer ")
                }
            });
        }
    }
}
